package ru.mcfr.oxygen.framework.operations;

import ro.sync.ecss.extensions.api.*;
import ro.sync.ecss.extensions.api.node.AuthorDocumentFragment;
import ro.sync.ecss.extensions.api.node.AuthorNode;

public class InsertLinkOperation implements AuthorOperation {


    public void doOperation(AuthorAccess authorAccess, ArgumentsMap args) throws IllegalArgumentException, AuthorOperationException {

        AuthorDocumentController controller = authorAccess.getDocumentController();
        String selectedText = authorAccess.getEditorAccess().getSelectedText();
        AuthorDocumentFragment nf = null;
        int where = authorAccess.getEditorAccess().getSelectionStart();

        try {
            AuthorNode selectedNode = controller.getNodeAtOffset(authorAccess.getEditorAccess().getCaretOffset());
            int startNodeOffset = authorAccess.getEditorAccess().getSelectionStart();
            int endNodeOffset = authorAccess.getEditorAccess().getSelectionEnd();
            if (selectedNode.getName() == "метка") {
                controller.delete(startNodeOffset, endNodeOffset - 1);
                nf = controller.createNewDocumentFragmentInContext(selectedNode.getTextContent(), startNodeOffset);
            } else {

                try {
                    if (!selectedText.isEmpty()) {
                        controller.delete(authorAccess.getEditorAccess().getSelectionStart(), authorAccess.getEditorAccess().getSelectionEnd() - 1);
                        nf = controller.createNewDocumentFragmentInContext("<метка id=\"\">" + selectedText + "</метка>", where);
                    } else
                        nf = controller.createNewDocumentFragmentInContext("<метка id=\"\"/>", authorAccess.getEditorAccess().getCaretOffset());
                } catch (Exception ex) {
                    ex.printStackTrace();
                    authorAccess.getWorkspaceAccess().showInformationMessage(ex.getMessage());
                }

            }
            if (nf != null)
                authorAccess.getDocumentController().insertFragment(where, nf);
        } catch (Exception e) {
            e.printStackTrace();
        }
//		} else if (args.getArgumentValue("mode") == "surround") {
//			// int[] xy = authorAccess.getWordAtCaret();
//		}

    }


    public ArgumentDescriptor[] getArguments() {
        ArgumentDescriptor[] res = {
                new ArgumentDescriptor("mode", ArgumentDescriptor.TYPE_STRING, "insert or surround"),
                new ArgumentDescriptor("content", ArgumentDescriptor.TYPE_FRAGMENT, "content to surround")
        };
        return res;
    }


    public String getDescription() {
        return "вставить метку";
    }

}
